package com.itbour.web.action.yjx.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.itbour.com.page.Page;
import com.itbour.common.base.BaseAction;
import com.itbour.common.util.MD5;
import com.itbour.common.util.StringUtils;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.dto.yjx.user.ItbQaInfoDto;
import com.itbour.dto.yjx.user.RedisReturnMes;
import com.itbour.dto.yjx.user.RocketTAG;
import com.itbour.service.yjx.user.SendRocketMesService;
import com.opensymphony.xwork2.ActionContext;
import com.qiniu.util.HttpRequest;

/**
 * 作者 ：李琦  
 * 缓存管理
 * 调查问卷管理
 */
public class RedisCacheManager extends BaseAction {

	/**
	 */
	private static final long serialVersionUID = 1L;
	private SendRocketMesService sendRocketMesService;
	private static final String SYNC_TAG = "sync"; // 同步缓存消息tag
	private static final String SWITCH_TAG = "switch"; // 切换缓存消息定义
	private static final String UDIEDB = "udiedb"; // 更新宕掉缓存消息
	private static final String CLEAR_API_CACHE = "clearapicache";// 清除接口缓存
	
	
	private static final String string = "yjxredis";// 加密字符串
	private JedisPool jedisPool;// redis 连接池
	private final static Integer REDIS_ONLINEDB_RECORD = RocketTAG.REDIS_ONLINEDB_RECORD;
	private final static Integer YJSC_REDIS_ONLINEDB_RECORD = RocketTAG.YJSC_REDIS_ONLINEDB_RECORD;
	private Object res = null;
	
	
	// 发送消息方法
	public void doSendMesg(Map<String, Object> parm) {
		sendRocketMesService.sendRocketMes(parm);
	}


	// 同步线上线下 redis缓存
	public String synRedisReq() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		String mdFiveValue = MD5.getMD5(string);
		if (secret!=null && secret.equals(mdFiveValue)){
			Jedis jedis = null;
			if (res != null) res =null;
			try {
				jedis = jedisPool.getResource();
				if (REDIS_ONLINEDB_RECORD == null){
					res = renderError("选库失败");
					return SUCCESS;
				}
				jedis.select(REDIS_ONLINEDB_RECORD);// 21号
				if (jedis.exists(RocketTAG.FLG_SYNC_ALLDBSTATE)){
					if (jedis.exists(RocketTAG.FLG_SYNC_ALLDBSTATE_END)){
						res = renderSucc("已同步完成");
						return SUCCESS;
					}
					res = renderSucc("正在同步中..");
					return SUCCESS;
				}
				Map<String, Object> parm = new HashMap<String, Object>();
				parm.put("mesg", SYNC_TAG); // 同步消息内容
				parm.put("tag", SYNC_TAG);// 同步消息 TAG
				sendRocketMesService.sendRocketMes(parm);
				res = renderSucc("开始同步缓存,请稍后查看");
			} catch (Exception e) {
				res = renderError("同步失败"+e.getMessage());
			} finally {
			    //注意这里不是关闭连接，在JedisPool模式下，Jedis会被归还给资源池。
			    if (jedis != null) jedis.close();
			}
		} else {
			res = renderError("秘钥验证失败");
		}
		return SUCCESS;
	}
	
	/**
	 * 一键秀 切换redis缓存
	 * @return
	 * @throws Exception
	 */
	public String switchRedisReq() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		String mdFiveValue = MD5.getMD5(string);
		if (secret!=null && secret.equals(mdFiveValue)){
			Jedis jedis = null;
			if (res != null) res =null;
			try {
				jedis = jedisPool.getResource();
				if (REDIS_ONLINEDB_RECORD == null){
					res = renderError("选库失败");
					return SUCCESS;
				}
				jedis.select(REDIS_ONLINEDB_RECORD);// 备注 记录库
				
				if (jedis.exists(RocketTAG.FLG_UPD_OFFLINE_START) || jedis.exists(RocketTAG.FLG_UPD_OFFLINE_END)){// 表示正在更新宕DB不能切换
					res = renderSucc("正在更新宕机DB,请稍后切换缓存");
					return SUCCESS;// 测试
				}
				String onLineRecord = jedis.get(RocketTAG.FLG_ONLINE_RECORD);// 线上库redis标记
				String offLineRecord = jedis.get(RocketTAG.FLG_OFFLINE_RECORD);// 线下库标记
				Map<String, Object> parm = new HashMap<String, Object>();
				parm.put("mesg", SWITCH_TAG);
				parm.put("tag", SWITCH_TAG);
				sendRocketMesService.sendRocketMes(parm);
				res = renderSucc("切换成功,当前线上库"+offLineRecord+"线下库"+onLineRecord);
			} catch (Exception e) {
				res = renderError("秘钥验证失败");
			} finally {
				if (jedis!=null)jedis.close();//释放资源
			}
		} else {
			res = renderError("秘钥验证失败");
		}
		return SUCCESS;
	}
	
	// 发送清理接口缓存消息
	public String clearApiCacheRedisReq() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		String mdFiveValue = MD5.getMD5(string);
		if (secret!=null && secret.equals(mdFiveValue)){ 
			if (res != null) res = null;
			try {
				Map<String, Object> parm = new HashMap<String, Object>();
				parm.put("mesg", CLEAR_API_CACHE);
				parm.put("tag", CLEAR_API_CACHE);
				sendRocketMesService.sendRocketMes(parm);
				res = renderSucc("清除成功");
			} catch (Exception e) {
				res = renderError("清除失败");
			}
		} else {
			res = renderError("秘钥验证失败");
		}
		return SUCCESS;
	}
	
	// 发送更新宕机缓存消息
	public String udiedbRedisReq() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		String mdFiveValue = MD5.getMD5(string);
		if (secret!=null && secret.equals(mdFiveValue)){
			Jedis jedis = null; if (res != null) res = null; 
			try {
				jedis = jedisPool.getResource();// 获取redis资源
				if (REDIS_ONLINEDB_RECORD ==null){
					res = renderError("选库失败");
					return SUCCESS;
				} 
				jedis.select(REDIS_ONLINEDB_RECORD);// 备注 记录库
				if (jedis.exists(RocketTAG.FLG_UPD_OFFLINE_START)){
					if (jedis.exists(RocketTAG.FLG_UPD_OFFLINE_END)){
//						this.writeJSON(RedisReturnMes.JSON_EXISTS);
						res = renderSucc("宕机DB已更新完毕");
						return SUCCESS;
					}
					res = renderSucc("宕机DB,正在更新中...");
					return SUCCESS;
				}
				String onLineRecord = jedis.get(RocketTAG.FLG_ONLINE_RECORD);// 线上库标记
				String offLineRecord = jedis.get(RocketTAG.FLG_OFFLINE_RECORD);// 线下库标记
				
				Map<String, Object> parm = new HashMap<String, Object>();
				parm.put("mesg", UDIEDB);// 发送更新宕机缓存消息
				parm.put("tag", UDIEDB);
				sendRocketMesService.sendRocketMes(parm);
				res = renderSucc("当前线上库"+onLineRecord+",开始更新DB"+offLineRecord+"号库,请稍等..");
			} catch (Exception e) {
				res = renderError("失败"+e.getMessage());
			} finally {
				if (jedis!=null){
					jedis.close();//释放资源
				}
			}
		} else {
			res = renderError("秘钥验证失败");
		}
		return SUCCESS;
	}
	
	/**
	 * @return 一键秀更新缓存
	 * @throws Exception
	 */
	public String upBuildCache() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user=(UserInfoDto)session.get("user");
		if (user!=null && user.getUser_id()!=null){
			Jedis jedis = null; 
			if (res != null) res =null;
			try {
				jedis = jedisPool.getResource();
				if (REDIS_ONLINEDB_RECORD == null){
					res = renderError("选库失败");
					return SUCCESS;
				}
				jedis.select(REDIS_ONLINEDB_RECORD);
				Map<String, Object> parm = new HashMap<String, Object>();
				if (jedis.exists(RocketTAG.FLG_UPTMPL_START)){
					if (jedis.exists(RocketTAG.FLG_UPTMPL_END)){
						jedis.del(RocketTAG.FLG_UPTMPL_START);// 删除开始标记
						jedis.del(RocketTAG.FLG_UPTMPL_END);// 删除结束标记
						res = renderSucc("已更新完毕");
						return SUCCESS;
					}
					res = renderSucc("上下架模板,正在更新中...");
					return SUCCESS;
				}
				res = renderSucc(sendRocketMesService.sendMesBuildCache(parm));
			} catch (Exception e) {
				res = renderError("更新失败"+e.getMessage());
			} finally {
				if (jedis!=null)jedis.close();//释放资源
			}
		} else {
			res = renderError("验证失败");
		}
		return SUCCESS;
	}
	
	/**	获取问卷调查信息
	 */
	private Map<String, Object> mapResult = new HashMap<String, Object>();
	private String findMobile;// 查询手机号
	private String findQaTmplId;// 查询问卷模板ID
	public String getQaInfo(){
		Map<String, Object> session=ActionContext.getContext().getSession();
		UserInfoDto user=(UserInfoDto)session.get("user");
		HttpServletRequest request=ServletActionContext.getRequest();
		if(user!=null && user.getUser_id()!=null){
			Integer pageNo = Integer.parseInt(request.getParameter("page"));
			Integer pageSize =Integer.parseInt(request.getParameter("rows"));
			Map<String,Object> parm=new HashMap<String, Object>();
			if (StringUtils.isNotEmpty(findMobile)){
				parm.put("mobile", findMobile);
			}
			if (StringUtils.isNotEmpty(findQaTmplId)){
				parm.put("qa_id", findQaTmplId);
			}
			Page page=sendRocketMesService.getQaInfo(parm, pageNo, pageSize);
			mapResult.put("total", page.getTotalCount());
			mapResult.put("rows",page.getResult());
		}
		return SUCCESS;
	}
	
	
	/**	获取问卷的问题模板
	 */
	private List<ItbQaInfoDto> listQaTmpl;
	public String getQaTmplInfo(){
		Map<String, Object> session=ActionContext.getContext().getSession();
		UserInfoDto user=(UserInfoDto)session.get("user");
		HttpServletRequest request=ServletActionContext.getRequest();
		if(user!=null && user.getUser_id()!=null){
			String qaId = request.getParameter("qaId");
			Map<String,Object> parm=new HashMap<String, Object>();
			if (StringUtils.isNotEmpty(qaId)){
				parm.put("qa_id", qaId);
				listQaTmpl = sendRocketMesService.getQaTmplInfo(parm);
			}
		}
		return SUCCESS;
	}
	
	/** *********************************  一键生成 发消息建立缓存		*************************************************************/
	// 一键生成 同步缓存
	public String synYJSCRedis() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		String flg = request.getParameter("flg");
		if (secret!=null){
			String mdFiveValue = MD5.getMD5(string);
			if (secret.equals(mdFiveValue)){
				Jedis jedis = null;
				try {
					jedis = jedisPool.getResource();
					if (YJSC_REDIS_ONLINEDB_RECORD == null){
						res = renderError("选库失败");
						return SUCCESS;
					} 
					jedis.select(YJSC_REDIS_ONLINEDB_RECORD);// 27
					
					if (flg != null){ // 删除标记
						jedis.del(RocketTAG.YJSC_FLAG);
						jedis.del(RocketTAG.YJSC_ENDFLAG);
					}
					
					String flg_AllDBstateOK = jedis.get(RocketTAG.YJSC_FLAG);
					String flg_AllDBstate = jedis.get(RocketTAG.YJSC_ENDFLAG);
					if (flg_AllDBstateOK!=null){
						if (flg_AllDBstate!=null){
							res = renderSucc("已同步完成");
							return SUCCESS;
						}
						res = renderSucc("正在同步模板中..");
						return SUCCESS;
					}
					Map<String, Object> parm = new HashMap<String, Object>();
					parm.put("mesg", RocketTAG.yjscsync); // 同步消息内容
					parm.put("tag", RocketTAG.yjscsync);// 同步消息 TAG
					boolean b = sendRocketMesService.sendRocketMes(parm);
					if (b) {
						res = renderSucc("已发送同步消息 开始同步");
					} else {
						res = renderSucc("消息发送失败 sorry");
					}
					return SUCCESS;
				} catch (Exception e) {
					System.out.println(e.getMessage());
					res = renderError(e.getMessage());
					return SUCCESS;
				} finally {
				    //注意这里不是关闭连接，在JedisPool模式下，Jedis会被归还给资源池。
				    if (jedis != null) jedis.close();
				}
			} else {
				res = renderError("验证秘钥失败");
				return SUCCESS;
			}
		} else {
			res = renderError("参数错误");
			return SUCCESS;
		}
	}
	
	/** 一键生成 修改/删除模板缓存
	 * 	author:liqi
	 */
	public String upYJSCRedisCache() throws Exception {
		Map<String, Object> session = ActionContext.getContext().getSession();
		UserInfoDto user=(UserInfoDto)session.get("user");
		if (user!=null && user.getUser_id()!=null){
			Jedis jedis = null;if (res !=null) res = null;
			try {
				jedis = jedisPool.getResource();
				if (YJSC_REDIS_ONLINEDB_RECORD == null){
					res = renderError("选库失败 请稍后重试");
					return SUCCESS;
				} 
				jedis.select(YJSC_REDIS_ONLINEDB_RECORD);
				Map<String, Object> parm = new HashMap<String, Object>();
				if (jedis.exists(RocketTAG.FLG_UPTMPL_START)){
					if (jedis.exists(RocketTAG.FLG_UPTMPL_END)){
						jedis.del(RocketTAG.FLG_UPTMPL_START);// 删除开始标记
						jedis.del(RocketTAG.FLG_UPTMPL_END);// 删除结束标记
						res = renderSucc("已更新完成 请转站APP查看");
						return SUCCESS;
					}
					res = renderSucc("正在更新中 请稍后");
					return SUCCESS;
				}
				res = renderSucc(sendRocketMesService.sendMesUpdateYjscTmpl(parm));
				return SUCCESS;
			} catch (Exception e) {
				res = renderError("更新失败"+e.getMessage());
				return SUCCESS;
			} finally {
				if (jedis!=null)jedis.close();
			}
		} else {
			res = renderError("更新失败");
		}
		return SUCCESS;
	}
	
	/** 一键生成  更新宕机DB */
	public String udieYJSCRedisDB() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		if (secret!=null){
			String mdFiveValue = MD5.getMD5(string);
			if (secret.equals(mdFiveValue)){
				Jedis jedis = null;
				try {
					jedis = jedisPool.getResource();// 获取redis资源
					if (YJSC_REDIS_ONLINEDB_RECORD ==null){
						res = renderError("获取资源库失败,稍后重试");
						return SUCCESS;
					}
					jedis.select(YJSC_REDIS_ONLINEDB_RECORD);// 备注 记录库
					if (jedis.exists(RocketTAG.YJSC_OFFINE_FLG)){
						if (jedis.exists(RocketTAG.YJSC_OFFINE_FLG_END)){
							res = renderSucc("已更新完毕");
							return SUCCESS;
						}
						res = renderSucc("正在更新宕机DB中...");
						return SUCCESS;
					}
					String offLineRecord = jedis.get(RocketTAG.YJSC_OFFINE_RECORD);// 线下库标记
					Map<String, Object> parm = new HashMap<String, Object>();
					parm.put("mesg", RocketTAG.yjscudiedb);// 发送更新宕机缓存消息
					parm.put("tag", RocketTAG.yjscudiedb);
					sendRocketMesService.sendRocketMes(parm);
					res = renderSucc("正在更新宕机DB"+offLineRecord+"号库");
					return SUCCESS;
				} catch (Exception e) {
					res = renderError("更新失败"+e.getMessage());
					return SUCCESS;
				} finally{
					if (jedis!=null){
						jedis.close();//释放资源
					}
				}
			} else {
				res = renderError("秘钥错误");
				return SUCCESS;
			}
		} else {
			res = renderError("参数错误");
			return SUCCESS;
		}
	}
	
	/**	@throws Exception	一键生成 清除接口缓存 */
	public String clearYJSCApiRedis() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		if (secret!=null){
			String mdFiveValue = MD5.getMD5(string);
			if (secret.equals(mdFiveValue)){
				try {
					Map<String, Object> parm = new HashMap<String, Object>();
					parm.put("mesg", RocketTAG.yjscclearapicache);
					parm.put("tag", RocketTAG.yjscclearapicache);
					sendRocketMesService.sendRocketMes(parm);
					res = renderSucc("清除成功");
				} catch (Exception e) {
					res = renderError("清除失败");
				}
			} else {
				res = renderError("秘钥验证失败");
			}
		} else {
			res = renderError("验证失败");
		}
		return SUCCESS;
	}
	
	
	/**	@throws Exception 一键生成  切换缓存  作者李琦*/
	public String switchYJSCRedis() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		if (secret!=null){
			String mdFiveValue = MD5.getMD5(string);
			if (secret.equals(mdFiveValue)){
				Jedis jedis = null; if (res !=null) res=null;
				try {
					jedis = jedisPool.getResource();
					if (YJSC_REDIS_ONLINEDB_RECORD ==null ) {
						res = renderError("选择库失败,请稍后重试");
						return SUCCESS;
					}
					jedis.select(YJSC_REDIS_ONLINEDB_RECORD);// 记录库
					if (jedis.exists(RocketTAG.YJSC_OFFINE_FLG)) {
						res = renderError("切换库正在更新,请稍后切换!");
						return SUCCESS;
					}
					String offLineRecord = jedis.get(RocketTAG.YJSC_OFFINE_RECORD);// 线下库标记
					Map<String, Object> parm = new HashMap<String, Object>();
					parm.put("mesg", RocketTAG.yjscswitch);
					parm.put("tag", RocketTAG.yjscswitch);
					sendRocketMesService.sendRocketMes(parm);
					res = renderSucc("切换成功,当前线上库为"+offLineRecord);
				} catch (Exception e) {
					res = renderError("切换失败");
				} finally {
					if (jedis!=null){
						jedis.close();//释放资源
					}
				}
			} else {
				res = renderError("秘钥验证失败");
			}
		} else {
			res = renderError("验证失败");
		}
		return SUCCESS;
	}
	
	/**
	 * 更新 推荐模板缓存
	 * 请求 api接口 /yjsc/v2/recommend/syncRecommendCache
	 * @return
	 */
	public String updateReCommondRedis(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String secret = request.getParameter("secret");
		if (secret!=null){
			String mdFiveValue = MD5.getMD5(string);
			if (secret.equals(mdFiveValue)) {
				String url = RocketTAG.RESTFUL_URL+"/yjsc/v2/recommend/updateRecommendCache";
				String param = "";// 没有参数
				try {
					HttpRequest.sendGet(url, param);
					res = renderSucc("请求成功,建立中");
				} catch (Exception e) {
					res = renderError("请求失败,请联系管理员");
				}
			} else {
				res = renderError("秘钥验证失败");
			}
		} else {
			res = renderError("验证失败");
		}
		return SUCCESS;
	}
	
	
	
	public Object getRes() {
		return res;
	}
	public void setRes(Object res) {
		this.res = res;
	}
	public List<ItbQaInfoDto> getListQaTmpl() {
		return listQaTmpl;
	}
	public String getFindQaTmplId() {
		return findQaTmplId;
	}
	public void setFindQaTmplId(String findQaTmplId) {
		this.findQaTmplId = findQaTmplId;
	}
	public String getFindMobile() {
		return findMobile;
	}
	public void setFindMobile(String findMobile) {
		this.findMobile = findMobile;
	}
	public void setListQaTmpl(List<ItbQaInfoDto> listQaTmpl) {
		this.listQaTmpl = listQaTmpl;
	}
	public Map<String, Object> getMapResult() {
		return mapResult;
	}
	public void setMapResult(Map<String, Object> mapResult) {
		this.mapResult = mapResult;
	}
	public SendRocketMesService getSendRocketMesService() {
		return sendRocketMesService;
	}
	public void setSendRocketMesService(
			SendRocketMesService sendRocketMesService) {
		this.sendRocketMesService = sendRocketMesService;
	}
	public JedisPool getJedisPool() {
		return jedisPool;
	}
	public void setJedisPool(JedisPool jedisPool) {
		this.jedisPool = jedisPool;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
}
